//
//  GroupMemberListViewController.m
//  Cunli
//
//  Created by 湛亚 on 16/1/8.
//  Copyright (c) 2016年 lilubin. All rights reserved.
//

#import "GroupMemberListViewController.h"
#import "PhoneNameTableViewCell.h"
#import "PeopleDataViewController.h"
#import "TongXunLu.h"

#import "UIImageView+WebCache.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface GroupMemberListViewController ()<IChatManagerDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>{
    
    UITableView *groupListTableView;
    BOOL isSearch;
    NSMutableArray *searchArray;
    UIView *tableHeaderView;
    UISearchBar *nameSearchBar;
    NSDictionary *huanXinDic;
}

- (void)unregisterNotifications;
- (void)registerNotifications;

@end

@implementation GroupMemberListViewController

- (void)registerNotifications {
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unregisterNotifications {
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)dealloc {
    [self unregisterNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self registerNotifications];
    self.title=@"群成员";
    huanXinDic = [[NSUserDefaults standardUserDefaults]objectForKey:@"huanXinInfo"];
    
    nameSearchBar=[[UISearchBar alloc]init];
    nameSearchBar.frame=CGRectMake(0, 0, SCREEN_WIDTH, 44);
    nameSearchBar.delegate=self;
    nameSearchBar.placeholder=@"搜索";
    [self.view addSubview:nameSearchBar];
    
    groupListTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    groupListTableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    groupListTableView.dataSource=self;
    groupListTableView.delegate=self;
    groupListTableView.backgroundColor=[UIColor whiteColor];
    groupListTableView.rowHeight=50;
    [self.view addSubview:groupListTableView];
 
}

#pragma mark - UITableView代理

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (self.isGroupOwner) {
        return 30;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (isSearch) {
        return searchArray.count;
    }
    return _groupListArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.isGroupOwner) {
        return @"左滑删除群成员";
    }else{
        return nil;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier=@"name";
    BOOL nibsRegistered=NO;
    if (!nibsRegistered) {
        UINib *nib=[UINib nibWithNibName:@"PhoneNameTableViewCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        nibsRegistered=YES;
    }
    PhoneNameTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    TongXunLu *user;
    if (isSearch) {
        user=[searchArray objectAtIndex:indexPath.row];
    }else{
        user=[_groupListArray objectAtIndex:indexPath.row];
    }
    cell.phoneImg.image=[UIImage imageNamed:@"default_touxiang"];
    cell.phoneImg.layer.cornerRadius = 20;
    cell.phoneImg.clipsToBounds = YES;
    cell.phoneNameLab.text=user.truename;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    TongXunLu *user;
    if (isSearch) {
        user=[searchArray objectAtIndex:indexPath.row];
    }else{
        user=[_groupListArray objectAtIndex:indexPath.row];
    }
    PeopleDataViewController *peopleVC=[[PeopleDataViewController alloc]init];
    peopleVC.touserid=[NSString stringWithFormat:@"%d",user.userid];
    [self.navigationController pushViewController:peopleVC animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isGroupOwner) {
        return UITableViewCellEditingStyleDelete;
    }else{
        return UITableViewCellEditingStyleNone;
    }
}

#pragma mark - 删除群成员

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    __weak typeof(self) weakSelf = self;
    
    TongXunLu *user;
    if (isSearch) {
        user=[searchArray objectAtIndex:indexPath.row];
    }else{
        user=[_groupListArray objectAtIndex:indexPath.row];
    }
    
    if ([user.huanxin_username isEqualToString:_groupOwner]) {
        [weakSelf showHint:@"不能删除群主!"];
        return;
    }
    
    [weakSelf showHudInView:weakSelf.view hint:NSLocalizedString(@"group.removingOccupant", @"deleting member...")];
    
    NSLog(@"删除名字%@",user.huanxin_username);
    NSArray *occupants = [NSArray arrayWithObject:user.huanxin_username];
    NSLog(@"删除群组id%@",weakSelf.groupId);
    [[EaseMob sharedInstance].chatManager asyncRemoveOccupants:occupants fromGroup:weakSelf.groupId completion:^(EMGroup *group, EMError *error) {
        
        [weakSelf hideHud];
        if (!error) {
                        
            if (isSearch) {
                [searchArray removeObjectAtIndex:indexPath.row];
                [groupListTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [weakSelf createGroupMemberListWithArray:group.occupants];
            }else{
                [_groupListArray removeObjectAtIndex:indexPath.row];
                [groupListTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
            
        }else{
            NSLog(@"%@",error.description);
            if (error.description) {
                [weakSelf showHint:error.description];
            }else{
                [weakSelf showHint:@"删除失败"];
            }
        }
    } onQueue:nil];
}

-(void)createGroupMemberListWithArray:(NSArray *)arr{
    
    [_groupListArray removeAllObjects];
    
    for (NSString *str in arr) {
        
        if ([huanXinDic objectForKey:[NSString stringWithFormat:@"%@name",str]]) {
            TongXunLu *user=[[TongXunLu alloc]init];
            user.huanxin_username=str;
            user.truename=[huanXinDic objectForKey:[NSString stringWithFormat:@"%@name",str]];
            user.pic=[huanXinDic objectForKey:[NSString stringWithFormat:@"%@pic",str]];
            NSString *useridString=[huanXinDic objectForKey:[NSString stringWithFormat:@"%@userid",str]];
            user.userid=[useridString intValue];
            [_groupListArray addObject:user];
        }
        
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //如果tableview停止滚动，开始加载图像
    [self loadImagesForOnscreenRows];
}

- (void)loadImagesForOnscreenRows
{
    
    //获取tableview正在window上显示的cell，加载这些cell上图像
    NSArray * visibleCells = [groupListTableView indexPathsForVisibleRows];
    TongXunLu *user;
    for (NSIndexPath * indexPath in visibleCells) {
        if (isSearch) {
            user=[searchArray objectAtIndex:indexPath.row];
        }else{
            user=[_groupListArray objectAtIndex:indexPath.row];
        }
        NSRange foundObj=[user.pic rangeOfString:@"default_touxiao.png" options:NSCaseInsensitiveSearch];
        if(!foundObj.length>0) {
            PhoneNameTableViewCell * cell = (PhoneNameTableViewCell *)[groupListTableView cellForRowAtIndexPath:indexPath];
            [cell.phoneImg setImageWithURL:[NSURL URLWithString:user.pic]];
        }
        
    }
}

//点击search按钮开始搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [self.view endEditing:YES];
    [self getSearchWorkAreaWithString:searchBar.text];
}

//本地搜索居住地或者搜索姓名添加群成员
-(void)getSearchWorkAreaWithString:(NSString *)str{
    
    NSMutableArray *nameSearchArray=[[NSMutableArray alloc]init];
    for (TongXunLu *user in _groupListArray) {
        NSRange foundObj=[user.truename rangeOfString:str options:NSCaseInsensitiveSearch];
        if(foundObj.length>0) {
            [nameSearchArray addObject:user];
        }
    }
    
    if (nameSearchArray.count<1) {
        
        [Config showHUDWithText:@"无搜索结果" andImage:@"done"];
        return;
        
    }else{
        
        //清空上次搜索结果,清空之前选中的成员
        searchArray=[[NSMutableArray alloc]initWithArray:nameSearchArray];
        isSearch=YES;
        [groupListTableView reloadData];
    }
}

//搜索框值变化时执行
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if ([searchBar.text isEqualToString:@""]) {
        isSearch=NO;
        searchArray=nil;
        [self.view endEditing:YES];
        [groupListTableView reloadData];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
